﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Net;
using SoccerScore.Compact.Linq;
using System.Linq;
using System.Data.SqlServerCe;
using HtmlAgilityPack;
using System.Data.SqlClient;
using Soccer_Score_Forecast.BulkSql;
using System.Xml.Linq;
using System.Configuration;

namespace Soccer_Score_Forecast
{
    public partial class Form1 : Form
    {
        #region html option 花我整1上午时间
        MacauslotToSql macau;
        private List<string> ParserMacau()
        {
            List<string> theList = new List<string>();
            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            HtmlNode.ElementsFlags.Remove("option");
            doc.LoadHtml(webBrowser2.Document.Body.InnerHtml);
            foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//select[@name='menu']//option"))
                if (node.InnerText.IndexOf("參考") == -1)
                    theList.Add(node.InnerText);
            return theList;
        }

        private void numericUpDown2_ValueChanged(object sender, EventArgs e)
        {
            #region 代码测试 ,自动解析所有类型的网页的表格 ,写入table or sqlserver
            try
            {
                checkedListBox2.Items.Clear();
                listBox3.Items.Clear();
                HtmlAgilityPackTableXpath tableXpath = new HtmlAgilityPackTableXpath(webBrowser2.Document.Body.InnerHtml,
                  (int)numericUpDown2.Value);
                foreach (var d in tableXpath.htmlTableAttDic.OrderByDescending(v => v.Value))
                {
                    listBox3.Items.Add(d.Key);
                    listBox3.Items.Add(d.Value.ToString());
                    //if (d.Key == tableXpath.maxKey || d.Key == tableXpath.secondKey) listBox3.Items.Add("--->" + d.Key + "--->" + d.Value.ToString());
                    //else listBox3.Items.Add(d.Key + "--->" + d.Value.ToString());
                }
                textBox4.Text = tableXpath.maxKey;
                textBox6.Text = tableXpath.secondKey;
                textBox7.Text = tableXpath.maxValue;
                textBox8.Text = tableXpath.secondValue;
                checkedListBox2.Items.Add(tableXpath.maxKey);
                checkedListBox2.Items.Add(tableXpath.secondKey);
            }
            catch { }
            #endregion
        }
        private void Macauslot_Click(object sender, EventArgs e)
        {
            try
            {
                int select = Int32.Parse(textBox2.Text); //只能通过这个textbox来循环，其他循环html的脚本有问题
                HtmlElement theList = webBrowser2.Document.GetElementsByTagName("select")[0];  //select 节点
                int optionmax = theList.GetElementsByTagName("option").Count;  //option 节点数量
                theList.Focus();
                if (select > optionmax) return;
                theList.GetElementsByTagName("option")[select].SetAttribute("selected", "true");//选定option
                theList.InvokeMember("onchange");    //不调用该方法网页将不刷新
                Application.DoEvents();
                macau = new MacauslotToSql(webBrowser2.Document.Body.InnerHtml);
                toolStripLabel2.Text = macau.updateMacauslot().ToString();
                select++;
                textBox2.Text = select.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(webBrowser2.Document.Body.InnerHtml);
                MessageBox.Show(ex.ToString());
            }
        }
        #endregion
        //C# 发送Http请求 - WebClient类 WebClient位于System.Net命名空间下，通过这个类可以方便的创建Http请求并获取返回内容。
        //一、用法1 - DownloadData
        private void button12_Click(object sender, EventArgs e)
        {
            string uri = "http://data1.7m.cn/Result_data/default_big.shtml?date=2003-01-01";
            System.Net.WebClient wc = new WebClient();
            byte[] bResponse = wc.DownloadData(uri);
            string strResponse = Encoding.ASCII.GetString(bResponse);
            richTextBox5.Text = strResponse;
        }
        //二、用法2 - OpenRead 
        private void button13_Click(object sender, EventArgs e)
        {
            string uri = "http://data1.7m.cn/Result_data/default_big.shtml?date=2003-01-01";

            WebClient wc = new WebClient();
            wc.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

            Stream st = wc.OpenRead(uri);
            StreamReader sr = new StreamReader(st);
            string res = sr.ReadToEnd();
            sr.Close();
            st.Close();
            richTextBox5.Text = res;
        }



        private void checkBox3_CheckedChanged(object sender, EventArgs e)
        {
            textBox3.Text = "http://live.aibo123.com/bifen/indexBeiDan.shtml?lang=&isc=";
            Thread.Sleep(500);//达不到要求的效果，后台axWebBrowser1，主程序全部暂停
        }

        public string aboutblank = "about:blank";

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            //DAL层，主要是负责数据的采集工作，


            while (webBrowser1.ReadyState != WebBrowserReadyState.Complete) return;
            richTextBox1.Text = webBrowser1.Document.Body.InnerHtml;
            while (richTextBox1.Text == null) return;
            toolStripStatusLabel1.Text = "download table complete!";

            //这里做处理，提前结束
            if (textBox1.Text == aboutblank)
            {
                insertComplete = true;
                toolStripStatusLabel1.Text = "update table complete!";
                return;
            }

            //在这里写入数据
            if (liveLib == true)
            {
                toolStripLabel2.Text = Update_live_Table(richTextBox1.Text).ToString();
                if (toolStripLabel2.Text == "0")
                    textBox1.Text = aboutblank;
            }
            else
            {
                toolStripLabel2.Text = Update_result_tb(richTextBox1.Text).ToString();
            }
            insertComplete = true;
            toolStripStatusLabel1.Text = "update table complete!";
        }

        private void button22_Click(object sender, EventArgs e)
        {
            webBrowser2.Navigate("http://live.aibo123.com/bifen/indexBeiDan.shtml?lang=&isc=");
        }

        private void button20_Click(object sender, EventArgs e)
        {
            try
            {
                WebRequest req = WebRequest.Create("http://buy.okooo.com/Lottery06/BJBetIndex.php?LotteryType=WDL");
                req.Proxy = null;
                OkooHtmlToSql okoo = null;
                using (WebResponse res = req.GetResponse())
                using (Stream s = res.GetResponseStream())
                using (StreamReader sr = new StreamReader(s, System.Text.Encoding.Default))
                    okoo = new OkooHtmlToSql(sr.ReadToEnd());
                toolStripLabel2.Text = okoo.updateLiveOkoo().ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {

                MessageBox.Show("OK");
            }
        }
        private void WebLiveDataGet()
        {
            string livedata =ConfigurationManager.AppSettings["livedata"].ToString(); 

            校验注册号代码Btn_Click();
            toolStripStatusLabel1.Text = "download table......";
            liveLib = true;
            textBox1.Text = livedata;
        }

        private void button31_Click(object sender, EventArgs e)
        {
            string PageUrl = "http://data1.7m.cn/Result_data/default_big.shtml?date=2003-07-01"; //需要获取源代码的网页
            WebRequest request = WebRequest.Create(PageUrl); //WebRequest.Create方法，返回WebRequest的子类HttpWebRequest
            WebResponse response = request.GetResponse(); //WebRequest.GetResponse方法，返回对 Internet 请求的响应
            Stream resStream = response.GetResponseStream(); //WebResponse.GetResponseStream 方法，从 Internet 资源返回数据流。 
            Encoding enc = Encoding.GetEncoding("GB2312"); // 如果是乱码就改成 utf-8 / GB2312
            StreamReader sr = new StreamReader(resStream, enc); //命名空间:System.IO。 StreamReader 类实现一个 TextReader (TextReader类，表示可读取连续字符系列的读取器)，使其以一种特定的编码从字节流中读取字符。 
            string res = sr.ReadToEnd();
            sr.Close();
            richTextBox5.Text = res;
        }
        bool datahtml;
        string resultdata;
        private void WebHistoryDataGet()
        {
            datahtml = false;
            liveLib = false;
            resultdata = ConfigurationManager.AppSettings["resultdata"].ToString();
            while (dateTimePicker1.Value.Date <= DateTime.Now.AddDays(-1).Date)
            {
                string strdp = dateTimePicker1.Value.ToString("yyyy-MM-dd");
                string dp = resultdata + strdp;
                listBox1.Items.Add(dp);
                dateTimePicker1.Value = dateTimePicker1.Value.AddDays(1);
            }
            toolStripProgressBar1.Maximum = listBox1.Items.Count;
            for (int i = 0; i < listBox1.Items.Count; i++)
            {
                toolStripStatusLabel1.Text = "download table......";
                toolStripProgressBar1.Value = i;
                textBox1.Text = listBox1.Items[i].ToString();
                while (!insertComplete) Application.DoEvents();
            }
            datahtml = true;
        }
        private void button4_Click(object sender, EventArgs e)
        {
            this.listView2.View = View.Details;
            listView2.Items.Clear();
            listView2.Items.Add("http://data.7m.cn/lottery/WSfc_fixture.shtml");
            listView2.Items.Add("http://buy.okooo.com/Lottery06/BJBetIndex.php?LotteryType=WDL");
            listView2.Items.Add("http://www.totochina.com/happypool/sp/sp.jsp");
            listView2.Items.Add("http://data1.7m.cn/fixture_data/default_big.shtml?date=1");

            listView2.Items.Add("");
            listView2.Items.Add("http://web.macauslot.com/soccer/html/predictions.html");
            //listView2.Items.Add("http://live.win.7m.cn/?view=all");
            //listView2.Items.Add("http://live.win.7m.cn/?view=jc");
            listView2.Items.Add("http://live.win.7m.cn/?view=sg");
            listView2.Items.Add("");
            listView2.Items.Add("http://live.win.7m.cn/?view=jc");
            listView2.Items.Add("");
            listView2.Items.Add("http://live2.7m.cn/cpk_ft.aspx?view=all&amp;match=&amp;line=no&amp;ordType=");
            listView2.Items.Add("http://live.aibo123.com/bifen/indexBeiDan.shtml?lang=&isc=");
            listView2.Items.Add("http://1x2.bet007.com/");
            string strdp = DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd");
            string dp = "http://data2.7m.cn/Result_data/default_big.shtml?date=" + strdp;
            listView2.Items.Add(dp);

            listView2.Columns[0].Width = 500;
        }

    }
}
